package com.zyz.O_网络编程.TCP.聊天室;

import java.io.*;
import java.net.Socket;
import java.util.List;

/**
 * @author: vick
 * @Date: 2025/4/17
 * @Description:
 * @version: 1.0
 */
public class MessageHandle extends Thread{
    private Socket socket;
    private String ip;

    private List<Socket> online;

    public MessageHandle(Socket socket, List<Socket> online) {
        this.socket = socket;
        this.online = online;
    }

    @Override
    public void run() {
        try {
            ip = socket.getInetAddress().getHostAddress();
            //告诉客户端 "已经上线了"
            sendToOther(ip + "已经上线了");


            //1. 接收客户端发送的消息
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str;
            while ((str = bufferedReader.readLine()) != null) {
                //给其他客户端发过去
                sendToOther(ip + ":" + str);
            }

            sendToOther(ip + "已经下线了");
        } catch (IOException e) {
            try {
                sendToOther(ip + "掉线了");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }finally {
            //从在线人员在移除
            online.remove(socket);
        }

    }

    public void sendToOther(String message) throws IOException {
        for (Socket on : online) {
            OutputStream outputStream = on.getOutputStream();
            PrintStream printStream = new PrintStream(outputStream);

            printStream.println(message);
        }
    }
}
